import { createSlice, PayloadAction, createSelector } from '@reduxjs/toolkit';
import type { CanvasConfig, PlatformInfo, DraftConfig, Keyframes, Materials, Draft, DraftState, DraftInfo, DraftStats, DraftMetadata } from './types/draft';

// 默认画布配置
const defaultCanvasConfig: CanvasConfig = {
    width: 1920,
    height: 1080,
    ratio: 'original',
};

// 默认平台信息
const defaultPlatformInfo: PlatformInfo = {
    app_id: 3704,
    app_source: 'lv',
    app_version: '5.9.0',
    os: 'windows',
};

// 默认配置
const defaultConfig: DraftConfig = {
    adjust_max_index: 1,
    attachment_info: [],
    combination_max_index: 1,
    export_range: null,
    extract_audio_last_index: 1,
    lyrics_recognition_id: '',
    lyrics_sync: true,
    lyrics_taskinfo: [],
    maintrack_adsorb: true,
    material_save_mode: 0,
    multi_language_current: 'none',
    multi_language_list: [],
    multi_language_main: 'none',
    multi_language_mode: 'none',
    original_sound_last_index: 1,
    record_audio_last_index: 1,
    sticker_max_index: 1,
    subtitle_keywords_config: null,
    subtitle_recognition_id: '',
    subtitle_sync: true,
    subtitle_taskinfo: [],
    system_font_list: [],
    video_mute: false,
    zoom_info_params: null,
};

// 默认关键帧
const defaultKeyframes: Keyframes = {
    adjusts: [],
    audios: [],
    effects: [],
    filters: [],
    handwrites: [],
    stickers: [],
    texts: [],
    videos: [],
};

// 默认素材
const defaultMaterials: Materials = {
    ai_translates: [],
    audio_balances: [],
    audio_effects: [],
    audio_fades: [],
    audio_track_indexes: [],
    audios: [],
    beats: [],
    canvases: [],
    chromas: [],
    color_curves: [],
    digital_humans: [],
    drafts: [],
    effects: [],
    flowers: [],
    green_screens: [],
    handwrites: [],
    hsl: [],
    images: [],
    log_color_wheels: [],
    loudnesses: [],
    manual_deformations: [],
    masks: [],
    material_animations: [],
    material_colors: [],
    multi_language_refs: [],
    placeholders: [],
    plugin_effects: [],
    primary_color_wheels: [],
    realtime_denoises: [],
    shapes: [],
    smart_crops: [],
    smart_relights: [],
    sound_channel_mappings: [],
    speeds: [],
    stickers: [],
    tail_leaders: [],
    text_templates: [],
    texts: [],
    time_marks: [],
    transitions: [],
    video_effects: [],
    video_trackings: [],
    videos: [],
    vocal_beautifys: [],
    vocal_separations: [],
};

// 初始状态
const initialState: DraftState = {
    currentDraft: null,
    draftMetadata: null,
    scriptData: null,
    draftId: null,
    isLoading: false,
    error: null,
};

// 创建默认草稿的工具函数
export const createDefaultDraft = (overrides: Partial<Draft> = {}): Draft => {
    const currentTime = Date.now();
    return {
        canvas_config: defaultCanvasConfig,
        color_space: 0,
        config: defaultConfig,
        cover: null,
        create_time: currentTime,
        duration: 0,
        extra_info: null,
        fps: 30,
        free_render_index_mode_on: false,
        group_container: null,
        id: window.crypto.randomUUID(),
        keyframe_graph_list: [],
        keyframes: defaultKeyframes,
        last_modified_platform: defaultPlatformInfo,
        platform: defaultPlatformInfo,
        materials: defaultMaterials,
        mutable_config: null,
        name: '',
        new_version: '110.0.0',
        relationships: [],
        render_index_track_mode_on: false,
        retouch_cover: null,
        source: 'default',
        static_cover_image_path: '',
        time_marks: null,
        tracks: [],
        update_time: currentTime,
        version: 360000,
        ...overrides,
    };
};

// 获取草稿基本信息
export const getDraftInfo = (draft: Draft): DraftInfo => {
    return {
        id: draft.id,
        name: draft.name,
        duration: draft.duration,
        fps: draft.fps,
        canvas_config: draft.canvas_config,
        create_time: draft.create_time,
        update_time: draft.update_time,
        source: draft.source,
        version: draft.version,
    };
};

// 获取草稿统计信息
export const getDraftStats = (draft: Draft): DraftStats => {
    const { materials, tracks } = draft;
    return {
        videoCount: materials.videos.length,
        audioCount: materials.audios.length,
        textCount: materials.texts.length,
        stickerCount: materials.stickers.length,
        effectCount: materials.effects.length,
        trackCount: tracks.length,
        totalMaterials: materials.videos.length + materials.audios.length + materials.texts.length + materials.stickers.length + materials.effects.length,
    };
};

// 创建slice
const draftSlice = createSlice({
    name: 'draft',
    initialState,
    reducers: {
        // 设置加载状态
        setLoading: (state, action: PayloadAction<boolean>) => {
            state.isLoading = action.payload;
        },

        // 设置错误信息
        setError: (state, action: PayloadAction<string | null>) => {
            state.error = action.payload;
        },

        // 创建新草稿
        createDraft: (state, action: PayloadAction<Partial<Draft>>) => {
            state.currentDraft = createDefaultDraft(action.payload);
            state.error = null;
        },

        // 加载草稿
        loadDraft: (state, action: PayloadAction<Draft>) => {
            state.currentDraft = action.payload;
            state.error = null;
        },

        // 更新整个草稿
        updateDraft: (state, action: PayloadAction<Draft>) => {
            if (state.currentDraft) {
                state.currentDraft = {
                    ...action.payload,
                    update_time: Date.now(),
                };
            }
        },

        // 更新草稿属性
        updateDraftProperty: <K extends keyof Draft>(
            state: DraftState,
            action: PayloadAction<{
                property: K;
                value: Draft[K];
            }>
        ) => {
            const { property, value } = action.payload;
            if (state.currentDraft) {
                state.currentDraft[property] = value;
                state.currentDraft.update_time = Date.now();
            }
        },

        // 更新草稿名称
        updateDraftName: (state, action: PayloadAction<string>) => {
            if (state.currentDraft) {
                state.currentDraft.name = action.payload;
                state.currentDraft.update_time = Date.now();
            }
        },

        // 更新画布配置
        updateCanvasConfig: (state, action: PayloadAction<Partial<CanvasConfig>>) => {
            if (state.currentDraft) {
                state.currentDraft.canvas_config = {
                    ...state.currentDraft.canvas_config,
                    ...action.payload,
                };
                state.currentDraft.update_time = Date.now();
            }
        },

        // 更新草稿配置
        updateDraftConfig: (state, action: PayloadAction<Partial<DraftConfig>>) => {
            if (state.currentDraft) {
                state.currentDraft.config = {
                    ...state.currentDraft.config,
                    ...action.payload,
                };
                state.currentDraft.update_time = Date.now();
            }
        },

        // 更新素材
        updateMaterials: (state, action: PayloadAction<Partial<Materials>>) => {
            if (state.currentDraft) {
                state.currentDraft.materials = {
                    ...state.currentDraft.materials,
                    ...action.payload,
                };
                state.currentDraft.update_time = Date.now();
            }
        },

        // 更新关键帧
        updateKeyframes: (state, action: PayloadAction<Partial<Keyframes>>) => {
            if (state.currentDraft) {
                state.currentDraft.keyframes = {
                    ...state.currentDraft.keyframes,
                    ...action.payload,
                };
                state.currentDraft.update_time = Date.now();
            }
        },

        // 更新轨道
        updateTracks: (state, action: PayloadAction<any[]>) => {
            if (state.scriptData) {
                state.scriptData.tracks = action.payload;
                state.scriptData.update_time = Date.now();
            }
        },

        // 清空草稿
        clearDraft: (state) => {
            state.currentDraft = null;
            state.error = null;
        },

        // 设置草稿元数据
        setDraftMetadata: (state, action: PayloadAction<DraftMetadata>) => {
            state.draftMetadata = action.payload;
            state.error = null;
        },

        // 清空草稿元数据
        clearDraftMetadata: (state) => {
            state.draftMetadata = null;
            state.error = null;
        },

        setScriptData: (state, action: PayloadAction<string>) => {
            state.scriptData = action.payload;
            state.error = null;
        },

        // 直接设置脚本数据对象
        setScriptDataObject: (state, action: PayloadAction<any>) => {
            state.scriptData = action.payload;
            state.error = null;
        },

        // 获取脚本数据（这里只是为了完整性，实际获取通过选择器）
        getScriptData: (state) => {
            // 这个 action 不需要修改 state，只是为了语义完整性
            return state.scriptData;
        },

        // 清空脚本数据
        clearScriptData: (state) => {
            state.scriptData = null;
            state.error = null;
        },

        // 设置草稿ID
        setDraftId: (state, action: PayloadAction<string | null>) => {
            state.draftId = action.payload;
            state.error = null;
        },
    },
});

// 导出actions和reducer
export const {
    setLoading,
    setError,
    createDraft,
    loadDraft,
    updateDraft,
    updateDraftProperty,
    updateDraftName,
    updateCanvasConfig,
    updateDraftConfig,
    updateMaterials,
    updateKeyframes,
    updateTracks,
    clearDraft,
    setDraftMetadata,
    clearDraftMetadata,
    setScriptData,
    setScriptDataObject,
    getScriptData,
    clearScriptData,
    setDraftId,
} = draftSlice.actions;

// 选择器函数 - 用于从 Redux state 中获取数据
export const selectCurrentDraft = (state: { draft: DraftState }) => state.draft.currentDraft;
export const selectDraftLoading = (state: { draft: DraftState }) => state.draft.isLoading;
export const selectDraftError = (state: { draft: DraftState }) => state.draft.error;
export const selectDraftInfo = (state: { draft: DraftState }) => {
    const draft = state.draft.currentDraft;
    return draft ? getDraftInfo(draft) : null;
};
export const selectDraftStats = (state: { draft: DraftState }) => {
    const draft = state.draft.currentDraft;
    return draft ? getDraftStats(draft) : null;
};
export const selectCanvasConfig = (state: { draft: DraftState }) => state.draft.scriptData?.canvas_config || null;
export const selectDraftConfig = (state: { draft: DraftState }) => state.draft.scriptData?.config || null;
export const selectMaterials = (state: { draft: DraftState }) => {
    return state.draft.scriptData?.materials || [];
};
export const selectKeyframes = (state: { draft: DraftState }) => state.draft.scriptData?.keyframes || null;
export const selectTracks = (state: { draft: DraftState }) => {
    return state.draft.scriptData?.tracks || [];
};
// 新增的选择器函数
export const selectDraftMetadata = (state: { draft: DraftState }) => state.draft.draftMetadata;
export const selectScriptData = (state: { draft: DraftState }) => state.draft.scriptData;
export const selectDraftId = (state: { draft: DraftState }) => state.draft.draftId;

// 获取指定轨道的指定片段
export const selectSegmentById = (trackId: string, segmentId: string) =>
    createSelector([(state: { draft: DraftState }) => state.draft.scriptData], (scriptData) => {
        if (!scriptData || !scriptData.tracks) {
            return null;
        }

        const track = scriptData.tracks.find((track: any) => track.id === trackId);
        if (!track || !track.segments) {
            return null;
        }

        return track.segments.find((segment: any) => segment.id === segmentId) || null;
    });

// 获取指定文本素材的配置
export const selectTextMaterialById = (materialId: string) =>
    createSelector([(state: { draft: DraftState }) => state.draft.scriptData], (scriptData) => {
        if (!scriptData || !scriptData.materials || !scriptData.materials.texts) {
            return null;
        }

        const textMaterial = scriptData.materials.texts.find((text: any) => text.id === materialId);
        if (!textMaterial || !textMaterial.content) {
            return null;
        }

        try {
            // 解析 content 中的 JSON 字符串
            const contentData = JSON.parse(textMaterial.content);
            return {
                ...textMaterial,
                parsedContent: contentData,
            };
        } catch (error) {
            console.error('解析文本素材内容失败:', error);
            return null;
        }
    });

export default draftSlice.reducer;
